<template>
  <div class="container">
    <!-- Header Section -->
    <Header />
    <!-- Main Section -->
    <main class="main">
      <div class="banner">
        <div class="left">
          <h1 class="headline">加入杰杰，开启旅程</h1>
          <p class="subheadline">新用户注册即享200元旅行礼包</p>
          <div class="benefits">
            <div class="benefit-item">
              <span class="icon">✓</span>
              <span>专属会员折扣</span>
            </div>
            <div class="benefit-item">
              <span class="icon">✓</span>
              <span>积分奖励计划</span>
            </div>
            <div class="benefit-item">
              <span class="icon">✓</span>
              <span>优先预订特权</span>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="register-card">
            <router-link to="/index" class="logo-link">
              <div class="logo-container">
                <img src="@/assets/logo.png" alt="杰杰去哪儿 Logo" class="header-logo">
                <div class="main-title">杰杰去哪儿</div>
              </div>
            </router-link>
            <h2>会员注册</h2>
            <form @submit.prevent="handleRegister">
              <div class="form-group">
                <input type="text" v-model="username" placeholder="用户名" class="input-field" />
                <span class="error-msg" v-if="usernameError">{{ usernameError }}</span>
              </div>
              <div class="form-group">
                <input type="email" v-model="email" placeholder="电子邮箱" class="input-field" />
                <span class="error-msg" v-if="emailError">{{ emailError }}</span>
              </div>
              <div class="form-group">
                <input type="password" v-model="password" placeholder="设置密码" class="input-field" />
                <span class="error-msg" v-if="passwordError">{{ passwordError }}</span>
              </div>
              <div class="form-group">
                <input type="password" v-model="confirmPassword" placeholder="确认密码" class="input-field" />
                <span class="error-msg" v-if="confirmPasswordError">{{ confirmPasswordError }}</span>
              </div>
              <div class="form-group verification-code">
                <input type="text" v-model="verificationCode" placeholder="邮箱验证码" class="input-field" />
                <button type="button" class="send-code-btn" :disabled="isCountingDown" @click="sendVerificationCode">
                  {{ isCountingDown ? `${countdown}秒后重发` : '获取验证码' }}
                </button>
                <span class="error-msg" v-if="verificationCodeError">{{ verificationCodeError }}</span>
              </div>
              <div class="agreement">
                <label>
                  <input type="checkbox" v-model="agreeTerms" />
                  我已阅读并同意<a href="#">《聚程旅行用户协议》</a>和<a href="#">《隐私政策》</a>
                </label>
                <span class="error-msg" v-if="!agreeTerms">请同意用户协议和隐私政策</span>
              </div>
              <button type="button" class="register-btn" @click="handleRegister">注 册</button>
              <div class="login-now">
                已有账号？<a href="#">立即登录</a>
              </div>
            </form>
          </div>
        </div>
      </div>
    </main>

    <!-- Footer Section -->
    <Footer />
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import axios from 'axios';
export default {
  name: "RegisterPage",
  components: {
    Header,
    Footer
  },
  data() {
    return {
      username: "",
      email: "",
      password: "",
      confirmPassword: "",
      phone: "",
      verificationCode: "",
      agreeTerms: false,
      usernameError: "",
      emailError: "",
      passwordError: "",
      confirmPasswordError: "",
      phoneError: "",
      verificationCodeError: "",
      isCountingDown: false,
      countdown: 60,
      uuid: ""
    };
  },
  methods: {
    handleRegister() {
      console.log('注册按钮被点击');
      // 表单验证
      this.resetErrors();
      let isValid = true;

      if (!this.username) {
        this.usernameError = "请输入用户名";
        isValid = false;
      }

      if (!this.email) {
        this.emailError = "请输入电子邮箱";
        isValid = false;
      } else if (!this.validateEmail(this.email)) {
        this.emailError = "请输入有效的电子邮箱";
        isValid = false;
      }

      if (!this.password) {
        this.passwordError = "请输入密码";
        isValid = false;
      } else if (this.password.length < 6) {
        this.passwordError = "密码长度不能少于6位";
        isValid = false;
      }

      if (!this.confirmPassword) {
        this.confirmPasswordError = "请确认密码";
        isValid = false;
      } else if (this.password !== this.confirmPassword) {
        this.confirmPasswordError = "两次输入的密码不一致";
        isValid = false;
      }

      if (!this.verificationCode) {
        this.verificationCodeError = "请输入验证码";
        isValid = false;
      }

      if (!this.agreeTerms) {
        isValid = false;
      }

      console.log('表单验证结果:', isValid);
      console.log('验证码:', this.verificationCode);
      console.log('UUID:', this.uuid);

      if (isValid) {
        // 先验证邮箱验证码
        if (this.verificationCode && this.uuid) {
          console.log('开始验证验证码');
          const verifyParams = new URLSearchParams();
          verifyParams.append('uuid', this.uuid);
          verifyParams.append('code', this.verificationCode);

          axios.post('/verify', verifyParams, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          })
              .then(verifyRes => {
                console.log('验证码验证结果:', verifyRes);
                if (verifyRes.code === 200) {
                  // 验证码验证成功，继续注册
                  this.registerUser();
                } else {
                  alert(verifyRes.data.msg || '验证码验证失败');
                }
              })
              .catch((error) => {
                console.error('验证码验证错误:', error);
                alert('验证码验证请求失败');
              });
        } else {
          // 没有验证码，直接注册
          console.log('直接注册用户');
          this.registerUser();
        }
      } else {
        console.log('表单验证失败');
      }
    },
    registerUser() {
      console.log('开始注册用户');
      // 处理注册逻辑，调用后端接口
      const user = {
        username: this.username,
        email: this.email,
        password: this.password,
      };
      console.log('注册用户数据:', user);
      axios.post('/register', user)
          .then(res => {
            console.log('注册响应:', res);
            // 假设后端Result结构为 { code: 200, data: ..., msg: ... }
            if (res.code === 200) {
              alert('注册成功，请登录！');
              this.$router.push('/login');
            } else {
              alert(res.data.msg || '注册失败');
            }
          })
          .catch((error) => {
            console.error('注册请求错误:', error);
            alert('邮箱重复，请重新输入邮箱');
          });
    },
    resetErrors() {
      this.usernameError = "";
      this.emailError = "";
      this.passwordError = "";
      this.confirmPasswordError = "";
      this.phoneError = "";
      this.verificationCodeError = "";
    },
    validateEmail(email) {
      const re = /^[1-9][0-9]{4,13}@qq\.com$/;
      return re.test(email);
    },
    validatePhone(phone) {
      const re = /^1[3-9]\d{9}$/;
      return re.test(phone);
    },
    startCountdown() {
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.isCountingDown = false;
          this.countdown = 60;
        }
      }, 1000);
    },
    sendVerificationCode() {
      this.emailError = '';
      if (!this.email) {
        this.emailError = "请输入电子邮箱";
        return;
      }

      if (!this.validateEmail(this.email)) {
        this.emailError = "请输入有效的电子邮箱";
        return;
      }

      this.isCountingDown = true; // 先禁用按钮，防止重复点击

      const params = new URLSearchParams();
      params.append('toEmail', this.email);

      axios.post('/send', params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
          .then(res => {
            if (res.code == 200) {
              this.uuid = res.data;
              this.startCountdown();
              alert('验证码已发送到您的邮箱');
            } else {
              this.isCountingDown = false;
              alert(res.msg || '发送验证码失败，请检查邮箱地址或稍后再试');
            }
          })
          .catch(() => {
            this.isCountingDown = false;
            alert('发送验证码请求失败，请稍后重试');
          });
    }

  }
};
</script>

<style scoped>/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

html, body {
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  color: #333;
}

.container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

/* Main 样式 */
.main {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 5%;
  background: url('https://images.unsplash.com/photo-1506929562872-bb421503ef21?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80') no-repeat center center;
  background-size: cover;
  position: relative;
}

.main::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.85);
}

.banner {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 1200px;
  position: relative;
  z-index: 1;
}

.left {
  flex: 1;
  padding: 40px;
  max-width: 600px;
  color: #333;
}

.headline {
  font-size: 42px;
  font-weight: 700;
  margin-bottom: 20px;
  line-height: 1.3;
  color: #0066ff;
}

.subheadline {
  font-size: 20px;
  color: #555;
  margin-bottom: 30px;
}

.benefits {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 30px;
}

.benefit-item {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #444;
}

.benefit-item .icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: #0066ff;
  color: white;
  border-radius: 50%;
  margin-right: 10px;
  font-size: 14px;
}

.right {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 450px;
}

.register-card {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
}

.logo-link {
  text-decoration: none;
  color: inherit;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 25px;
}

.header-logo {
  height: 35px;
}

.main-title {
  font-size: 32px;
  font-weight: bold;
  color: #0066ff;
  background: linear-gradient(to right, #0066ff, #00ccff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.register-card h2 {
  font-size: 24px;
  margin-bottom: 30px;
  color: #333;
  text-align: center;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.input-field {
  width: 100%;
  padding: 14px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 15px;
  transition: all 0.3s;
  background-color: #f9f9f9;
}

.input-field:focus {
  border-color: #0066ff;
  box-shadow: 0 0 0 3px rgba(0, 102, 255, 0.1);
  background-color: white;
}

.error-msg {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.register-btn {
  width: 100%;
  padding: 14px;
  background-color: #0066ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 20px;
}

.register-btn:hover {
  background-color: #0052cc;
}

.verification-code {
  display: flex;
  gap: 10px;
}

.send-code-btn {
  flex-shrink: 0;
  padding: 0 15px;
  background-color: #f0f0f0;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.send-code-btn:hover:not(:disabled) {
  background-color: #e0e0e0;
}

.send-code-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.agreement {
  margin-top: 15px;
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.agreement a {
  color: #0066ff;
  text-decoration: none;
}

.agreement a:hover {
  text-decoration: underline;
}

.agreement input {
  margin-right: 5px;
}

.login-now {
  text-align: center;
  margin-top: 25px;
  color: #666;
  font-size: 14px;
}

.login-now a {
  color: #0066ff;
  text-decoration: none;
  font-weight: 500;
}

.login-now a:hover {
  text-decoration: underline;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .footer-content {
    justify-content: flex-start;
  }

  .footer-section {
    flex: 0 0 50%;
  }
}

@media (max-width: 768px) {
  .banner {
    flex-direction: column;
    align-items: center;
  }

  .left {
    text-align: center;
    padding: 20px;
    margin-bottom: 30px;
  }

  .benefits {
    align-items: center;
  }

  .register-card {
    padding: 30px;
  }
}

@media (max-width: 576px) {
  .headline {
    font-size: 32px;
  }

  .subheadline {
    font-size: 18px;
  }
}
</style>